<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<html:header title="序列号录入">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">

    <style type="text/css">
        .managerSn{
            cursor: pointer;
            color: #01AAED;
            text-decoration: none;
            font-size: 12px;
        }
        .managerSn:hover {
            color: #FF5722;
        }

        .button-bottom{
            color: #393D49;
            cursor: pointer;
            font-size: 12px;
            padding: 10px 14px;
            margin: 4px;
            border: 1px solid #d2d2d2;
            border-radius: 2px;
        }
        .button-bottom:hover{
            color: #5FB878;
        }

        .button-bottom-blue{
            cursor: pointer;
            color: #ffffff;
            font-size: 12px;
            background-color: #1E9FFF;
            padding: 10px 20px;
            margin: 2px;
            border-radius: 2px;
        }
        .button-bottom-blue:hover{
            background-color: #5FB878;
            color: #ffffff;
        }
    </style>

    <script>
        let houseId = "${houseVoList[0].id}";
        //map : key-houseId   value-sn
        let snData = {};
        let used_map = {};

        jQuery(function () {
            if ("${houseId}"!=""){
                houseId = "${houseId}";
                //不需要选择仓库了，直接显示sn号录入
                $("#snDiv").css("display","block");
                $("#houseDiv").css("display","none");
            } else {
                //未传入houseId，先显示仓库选择界面
                $("#snDiv").css("display","none");
                $("#houseDiv").css("display","block");
            }

            if ("${type}" == "2"){
                $("#selectHouse").css("display","none");
            }

            $("#help-import-div").hide();
            $(".help-import").mouseenter(function () {
                $("#help-import-div").show();
            });
            $(".help-import").mouseleave(function () {
                $("#help-import-div").hide();
            });
            let $tr = $("[houseId='"+houseId+"']");
            console.log("houseName:"+$tr.attr("houseName"));
            $("#houseName").html($tr.attr("houseName"));
        });


        layui.use(['table','element'], function() {
            var table = layui.table;
            table.render({
                elem: '#table'
                , id: "table"
                , data: []
                , page: true
                , cols: [[ //标题栏
                    {type: 'checkbox'}
                    , {field: 'id', hide: true}
                    , {field: 'index', title: '序号', type: 'numbers'}
                    , {field: 'sn', title: '序列号', edit: "text"}
                    , {field: 'remark', title: '序列号备注', edit: "text"}
                ]]
                , done: function (res, curr, count) {
                    addedSnNum = count;
                    snNumberProcess();
                }
            });
        });

        function snNumberProcess() {
            console.log(snData);
            for (var key in snData){
                $("[houseId='"+key+"']").find(".snNumber").html(snData[key].length);
            }
        }

        //检查是否有重复，重复的就舍弃，所有仓库的sn都要检查一遍
        function checkSn(sn) {
            for (var key in snData){
                for (var i=0;i<snData[key].length;i++){
                    if (sn == snData[key][i].sn){
                        return false;
                    }
                }
            }

            for (var key in used_map){
                for (var i=0;i<used_map[key].length;i++){
                    if (sn == used_map[key][i].sn){
                        return false;
                    }
                }
            }

            return true;
        }

        function setDataToTable(selectList,useMap) {
            $.each(selectList, function (i,d) {
                if (snData[d.houseId] == undefined){
                    snData[d.houseId] = [];
                }
                snData[d.houseId].push(d);
            });

            $.each(useMap["${goodsId}"], function (i,d) {
                if (used_map[d.houseId] == undefined){
                    used_map[d.houseId] = [];
                }
                used_map[d.houseId].push(d);
            });


            setTimeout(function () {
                reloadTable();
            },50);
        }


        function reloadTable() {
            layui.use(['table','element'], function() {
                var table = layui.table;
                table.reload('table', {
                    data: snData[houseId] == undefined ? [] : snData[houseId],
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            });
        }

        function processSnArray(snArray, process){
            if (snArray == undefined || snArray == null){
                return [];
            }
            let data = [];
            let sns = [];
            let repeat = false;
            for (var i=0;i<snArray.length;i++){
                let sn = snArray[i];
                if (sn != "" && /^[0-9a-zA-Z]+$/.test(sn)) {
                    if (checkSn(sn)){
                        data.push({sn: sn, remark: '',status:1,houseId:houseId,goodsId:"${goodsId}"});
                        sns.push(sn);
                    } else {
                        repeat = true;
                    }
                }
            }

            if (repeat){
                tip("序列号已被经录");
            }
            if (data.length > 0) {
                //去后台检查sn是都有重复
                post("${baseUrl}house/goodsSn/checkRepeat.action?goodsId=${goodsId}",sns,function (res) {
                    if (res.code == 1){
                        process(data);
                    } else {
                        errTip(res.msg);
                    }
                });
            }
        }

        /**
         * 插入数据到全局变量
         * @param data
         */
        function batchInsert(data) {

            $("[name='snInput']").val("");
            $("[name='prefix']").val("");
            $("[name='start']").val("");
            $("[name='number']").val("");
            if (data == undefined){
                return;
            }
            let stockNum = parseInt($("#stockNumber").html());
            console.log("batchInsert: stockNum-"+stockNum + "    data.length-"+data.length);
            //商品编辑时，需要增加一些判断
            if ("${type}" == "1"){
                if (stockNum == addedSnNum){
                    errTip("库存与序列号数量一致，不再继续添加");
                    return;
                } else if (stockNum-addedSnNum < data.length){
                    tip("序列号数量过多，自动截断多余序列号");
                    data = data.slice(0,stockNum-addedSnNum);
                }
            }

            if (data.length > 0) {
                //数组合并
                if (snData[houseId] == undefined){
                    snData[houseId] = [];
                }
                snData[houseId] = snData[houseId].concat(data);
            }

            reloadTable();
        }

        function batchDelete(data) {
            let map = {};
            for (var i=0;i<data.length;i++){
                map[data[i].sn] = true;
            }

            let temp = [];
            for (var i=0;i<snData[houseId].length;i++){
                let b = snData[houseId][i].sn;
                let a = map[snData[houseId][i].sn];
                if (!map[snData[houseId][i].sn]) {
                    temp.push(snData[houseId][i]);
                }
            }
            snData[houseId] = temp;
            reloadTable();
        }
    </script>

</html:header>
<body style="background-color: #ffffff; padding-bottom: 30px;">
    <div id="snDiv" style="display: block">
        <div style="color: #999999;margin-bottom: 20px;">
            [仓库：<span id="houseName" style="color: #FF5722;"></span>]
            <span style="padding-left: 10px;">库存数量 <span id="stockNumber" style="color:#FF5722">0</span></span>
        </div>
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">序列号录入</li>
                <li>批量录入</li>
                <li>文件导入</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <div class="layui-row">
                        <div class="layui-col-xs10">
                            <input type="text" name="snInput" class="layui-input">
                        </div>
                        <div class="layui-col-xs2" style="padding-left: 4px;">
                            <a class="layui-btn add">添加</a>
                        </div>
                    </div>
                    <div style="color: #aaaaaa;padding-top: 20px;">请在上方输入序列号，多个序列号可用英文逗号“,”区分，同时加入</div>
                </div>
                <div class="layui-tab-item">
                    <div class="layui-tab-item layui-show">
                        <div class="layui-row">
                            <div class="layui-col-xs3">
                                前缀
                                <div class="layui-input-inline">
                                    <input type="text" name="prefix" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-col-xs3">
                                起始号
                                <div class="layui-input-inline">
                                    <input type="number" name="start" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-col-xs4">
                                个数
                                <div class="layui-input-inline">
                                    <input type="number" name="number" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-col-xs2" style="padding-left: 4px;">
                                <a class="layui-btn batchAdd">添加</a>
                            </div>
                        </div>
                        <div style="color: #aaaaaa;padding-top: 20px;">前缀可不填，序列号以递增方式添加</div>
                    </div>

                </div>

                <div class="layui-tab-item">

                    <div class="layui-row">
                        <div class="layui-col-xs8">
                            <div style="color: #01AAED;font-size: 12px; position: relative;" class="help-import">
                                txt文本示例
                                <div id="help-import-div" style="position: absolute; top: 0px; left: 60px;z-index: 9999;">
                                    <img src="${baseUrl}images/sn_import_example.jpg">
                                </div>
                            </div>
                            <div style="color: #2F4056;font-size: 12px;">
                                1.系统支持导入txt文本，且每行输入一个序列号。<br>
                                2.系统只允许上传一个txt文件</div>
                        </div>
                        <div class="layui-col-xs4" style="padding-left: 4px;">
                            <a id="selectSnTxt" class="layui-btn batchImport">选择并导入</a>
                        </div>
                        <div style="display: none">
                            <input type="file" accept=".txt" id="snTxtInput">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <hr>
        <table class="layui-hide" id="table" lay-filter="table"></table>

        <div style="padding-top: 10px;margin-bottom: 20px;">
            <div style="float: left;">
                <a id="batchDelete" class="button-bottom" style="margin-left: 0">批量删除</a>
                <a id="selectHouse" class="button-bottom">选择仓库</a>
            </div>

            <div style="float:right;">
                <a id="sure" class="button-bottom-blue" style="margin-right: 0">确认</a>
                <a id="backParent" class="button-bottom" style="margin-right: 0">取消</a>
            </div>

            <div style="clear: both"></div>
        </div>

        <script>
            $("#selectHouse").click(function () {
                $("#snDiv").css("display","none");
                $("#houseDiv").css("display","block");
            });


            $(".add").click(function () {
                var snInput = $("[name='snInput']").val();
                if (snInput == "") {
                    tip("序列号不能为空");
                    return ;
                }

                processSnArray(snInput.split(","), function (data) {
                    batchInsert(data);
                });
            });

            $(".batchAdd").click(function () {
                var prefix = $("[name='prefix']").val();
                var start = $("[name='start']").val();
                var number = $("[name='number']").val();

                if (prefix == "") {
                    tip("开始序列号不能为空");
                    return ;
                }
                if (!isNumber(start)) {
                    tip("仅允许输入数字");
                    return ;
                }

                if (number == "") {
                    tip("个数不能为空");
                    return ;
                }
                if (!isNumber(number)) {
                    tip("仅允许输入数字");
                    return ;
                }
                if (parseInt(number) < 1) {
                    tip("个数必需大于1");
                    return ;
                }

                if (parseInt(number) > 50000) {
                    tip("个数必需小于50000");
                    return ;
                }

                let temp = [];
                for(var i = 0; i < parseInt(number); i++) { // 追加新数据
                    var sn = prefix;
                    sn +=  (parseInt(start)+i);
                    temp.push(sn);
                }
                processSnArray(temp, function (data) {
                    batchInsert(data);
                });
            });

            $("#selectSnTxt").click(function () {
                $("#snTxtInput").click();
            });
            $("#snTxtInput").change(function () {
                tipLoad("文件处理中...");
                var file = this.files[0];
                var reader = new FileReader();//新建一个FileReader
                reader.readAsText(file, "UTF-8");//读取文件
                reader.onload = function(evt) { //读取完文件之后会回来这里
                    var fileString = evt.target.result; // 读取文件内容
                    var snArray = fileString.split("\r\n");
                    console.log(snArray.length);
                    processSnArray(snArray, function (data) {
                        batchInsert(data);
                    });
                }
            });

            $("#batchDelete").click(function () {
                var checkStatus = layui.table.checkStatus('table');
                batchDelete(checkStatus.data);
            });

            $("#sure").click(function () {
                console.log("table.cache.data："+ JSON.stringify(layui.table.cache.table));
                if (window.parent.processSnImport != undefined){
                    let data=[];
                    for (var key in snData){
                        for (var i=0;i<snData[key].length;i++){
                            data.push(snData[key][i]);
                        }
                    }
                    window.parent.processSnImport(data);
                }
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            $("#backParent").click(function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });
        </script>
    </div>


    <div id="houseDiv" style="display: none">
        <table class="layui-table">
            <thead>
            <tr>
                <th>门店</th>
                <th>仓库</th>
                <th>当前库存</th>
                <th>序列号个数</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <c:forEach var="houseVo" items="${houseVoList}">
                <tr houseId="${houseVo.id}" houseName="${houseVo.store.name}>${houseVo.name}">
                    <td>${houseVo.store.name}</td>
                    <td >${houseVo.name}</td>
                    <td class='stockNumber'>0</td>
                    <td class='snNumber'>0</td>
                    <td><a class='managerSn'>管理序列号</a></td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
        <hr style="margin-top: 20px;">
        <a id="snImport" class="button-bottom-blue" >序列号录入</a>
        <a id="back" class="button-bottom" >取消</a>
        <script>
            get("${baseUrl}goodsStock/listByGoods.action?goodsId=${goodsId}", function (resp) {
                if (resp.code == 1) {
                    console.log("库存:" + JSON.stringify(resp.data));
                    $.each(resp.data, function (i, goodsStock) {
                        if (houseId == goodsStock.houseId){
                            $("#stockNumber").html(goodsStock.num);
                        }
                        $("tr[houseId='"+goodsStock.houseId+"']").find(".stockNumber").html(goodsStock.num);
                    });
                }
            });
            $("#back").click(function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });
            $("#snImport").click(function () {
                $("#snDiv").css("display","block");
                $("#houseDiv").css("display","none");
            });
            $(".managerSn").click(function () {
                $("#snDiv").css("display","block");
                $("#houseDiv").css("display","none");
                houseId = $(this).parents("tr").attr("houseId");
                $("#houseName").html($(this).parents("tr").attr("houseName"));
                $("#stockNumber").html($(this).parents("tr").find(".stockNumber").html());

                reloadTable();
            });

        </script>
    </div>
</body>
<html:loading/>
</html>